package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.IdeaReplay;
import service.UserService;
import util.db.DBhelp;
import util.db.RowMapper;

public class IdeaReplayDao {

	
	private DBhelp<IdeaReplay> dBhelp = new DBhelp<IdeaReplay>();
	
	
	private class IdeaReplayRowMapper implements RowMapper<IdeaReplay>{

		public IdeaReplay mapRow(ResultSet resultSet) throws SQLException {
			IdeaReplay ideaReplay = new IdeaReplay();
			ideaReplay.setId(resultSet.getString("id"));
			ideaReplay.setContent(resultSet.getString("content"));
			ideaReplay.setCreatetime(resultSet.getString("createtime"));
			ideaReplay.setUserid(resultSet.getString("userid"));
			ideaReplay.setIdeaid(resultSet.getString("ideaid"));
			return ideaReplay;
		}
	}


	public void save(IdeaReplay ideaReplay) {
		String sql = "insert into t_ideareplay (id,content,createtime,userid,ideaid)values(?,?,?,?,?)";
		dBhelp.update(sql, ideaReplay.getId(),ideaReplay.getContent(),ideaReplay.getCreatetime(),ideaReplay.getUserid(),ideaReplay.getIdeaid());
	}


	public List<IdeaReplay> findIdeaReplayByIdeaid(String id) {
		String sql = "select * from t_ideareplay where ideaid=? order by createtime desc";
		return dBhelp.executeQueryForList(sql, new RowMapper<IdeaReplay>() {

			public IdeaReplay mapRow(ResultSet resultSet) throws SQLException {
				IdeaReplay ideaReplay = new IdeaReplay();
				ideaReplay.setId(resultSet.getString("id"));
				ideaReplay.setContent(resultSet.getString("content"));
				ideaReplay.setCreatetime(resultSet.getString("createtime"));
				ideaReplay.setUserid(resultSet.getString("userid"));
				ideaReplay.setIdeaid(resultSet.getString("ideaid"));
				ideaReplay.setUser(new UserService().findUserById(resultSet.getString("userid")));
				return ideaReplay;
			}
		}, id);
	}


	public void removeByideaid(String id) {
		String sql = "delete from t_ideareplay where ideaid=?";
		dBhelp.update(sql, id);
	}
}
